<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\App;
use app\common\model\Assets;

use app\common\builder\TableBuilder;
use app\common\builder\TableFront;

class Exchange extends Base
{
    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Exchange';

    //关联模型
    protected $hasOne = ['user'];


    public function index()
    {
        return $this->setTable();
    }

    public function setTable()
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'nickname', 'title' => '昵称', 'templet' => '<div>{{d.user.nickname}}</div>'])
            ->addRow(['field' => 'code', 'title' => '编号', 'templet' => '<div>{{d.user.code}}</div>'])
            ->addRow(['field' => 'mobile', 'title' => '手机号', 'templet' => '<div>{{d.user.mobile}}</div>'])
            ->addRow(['field' => 'account', 'title' => '转出账户'])
            ->addRow(['field' => 'take_account', 'title' => '转入账户'])
            ->addRow(['field' => 'amount', 'title' => '转换金额'])
            ->addRow(['field' => 'cost', 'title' => '手续费'])
            ->addRow(['field' => 'create_time', 'fixed' => 'right', 'title' => '转换时间', 'width' => 150]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addTopButtons(['export'])
            ->setSearch($this->setSearch())
            ->fetch();
    }

    public function setSearch()
    {
        return TableFront::getInstance()
            ->setSearch(['uid', '会员编号/昵称/手机号', 'input', '', '\app\common\model\User', 'code|nickname|mobile,id'])
            ->setSearch(['account', '转出账户', 'select', Assets::getFields(3)])
            ->setSearch(['take_account', '转入账户', 'select', Assets::getFields(3)]);
    }


    public function export()
    {
        $name = '转换列表' . date('Y-m-d H:i:s');
        $s = $this->setMap($this->request->get('name'));
        $s['with'] = $this->hasOne;
        $title = TableFront::getInstance()->getFieldTable($this->request->get('name'));
        if (empty($title)) {
            return json(['code' => -1, 'msg' => '导出失败，请清除缓存后重试！']);
        }

        $s['filed'] = 'id,uid,account,take_account,cost,amount,create_time';
        $list = $this->model::getSelect($s);

        foreach ($list['data'] as &$v) {
            $v['code'] = $v->user->code;
            $v['nickname'] = $v->user->nickname;
            $v['mobile'] = $v->user->mobile;
            unset($v->uid);
            unset($v->user);
        }

        return json(['code' => 1, 'result' => ['data' => $list['data']->toArray(), 'title' => $title, 'name' => $name]]);
    }

}
